﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Core
{
    public class TrailSystem : Core.Component, IAwake
    {
        private const string ResPath = "Res/Prefabs/Misc/trail.prefab";
        private readonly List<Vector3> paths = new();

        private GameObject gameObject;
        private Transform transform;

        private Coroutine coroutine;

        public void Awake()
        {
            var asset = G.Res.LoadSync(ResPath);
            gameObject = GameObject.Instantiate(asset.Obj) as GameObject;
            transform = gameObject?.transform;
        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            S.mono.StopCoroutine(coroutine);
            coroutine = null;

            base.Dispose();
        }

        public void Show(List<Vector3> points)
        {
            if (points.Count == 0 || transform == null) return;

            paths.Clear();
            paths.AddRange(points);

            Utils.Trans.SetActive(gameObject, false);
            transform.position = paths[0];
            Utils.Trans.SetActive(gameObject, true);

            coroutine = S.mono.StartCoroutine(MoveAnimate(0));
        }

        private IEnumerator MoveAnimate(int index)
        {
            while (true)
            {
                var posTo = paths[index];
                posTo.z = 99;

                transform.position = posTo;

                yield return null;

                index++;
                if (index >= paths.Count)
                {
                    break;
                }
            }
        }
    }
}
